package conn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayDeque;
import java.util.Queue;

import org.apache.log4j.Logger;


public class ConnectionPool {
	public ConnectionPool( String name, String conn_string, int count)
	{
		this.name = name;
		this.conn_string = conn_string;
		this.count = count;
	}
	public Connection GetConnection() throws DBConnException
	{
		Connection conn;
		synchronized(pool)
		{
			conn = pool.poll();				
		}
		
		if ( conn != null )
		{
			try {
				if ( !conn.isClosed() )
					return conn;
			} catch (SQLException e) {
			}
			conn = null;
		}

		try {
			conn = DriverManager.getConnection(conn_string);
			return conn;
		} catch (SQLException e) {
			log.error("get conn failed! name is "+name);
			throw new DBConnException(e);
		}
	}
	
	public void BackConnection(Connection conn)
	{
		if ( conn == null )
			return;
		synchronized(pool)
		{
			if ( pool.size() < count )
			{
				pool.add(conn);
				return;
			}
		}
		try {
			conn.close();
		} catch (SQLException e) {
			log.error(name, e);
		}
	}	
	public int GetSize()
	{
		synchronized(pool)
		{
			return pool.size();
		}
	}
	public String GetName()
	{
		return name;
	}
	public int GetCount()
	{
		return count;
	}
	private static Logger log = Logger.getLogger(ConnectionPool.class);
	private String name, conn_string;
	private int count;
	private Queue<Connection> pool = new ArrayDeque<Connection>();
}
